/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

public class ChartActionBean extends StandardActionBean {
  private String id;
  private int width;
  private int height;

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public int getWidth() {
    return width;
  }

  public void setWidth(int width) {
    this.width = width;
  }

  public int getHeight() {
    return height;
  }

  public void setHeight(int height) {
    this.height = height;
  }

  public static String storeChart(SessionContext session, JFreeChart chart) {
    String chartId = UUID.randomUUID().toString();
    session.setAttribute(chartId, chart);
    return chartId;
  }

  public Resolution getChart() {
    JFreeChart chart = (JFreeChart) request().getSession().getAttribute(id);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    try {
      ChartUtilities.writeChartAsPNG(stream, chart, width, height);
    } catch (IOException e) {
      LogFactory.getLog(getClass()).error("Error creating chart for uuid " + id, e);
      throw new RuntimeException(e);
    }
    return new StreamingResolution("image/png", new ByteArrayInputStream(stream.toByteArray()));
  }
}
